<template>
	<view class="vote-result-page">
		<custom-navbar title="投票结果" bgColor="#fff" textColor="#333">
		</custom-navbar>
		<!-- 活动信息卡片 -->
		<view class="voteInfo-card">
			<view class="voteInfo-status" :class="voteInfo.status == '1' ? 'active' : 'ended'">
				{{ voteInfo.status == '1' ? '投票进行中' : '投票已结束' }}
			</view>
			<h1 class="voteInfo-title">投票主题：{{ voteInfo.voteTitle }}</h1>
			<view class="voteInfo-meta">
				<view class="meta-item">
					<uni-icons type="person" size="16" color="#666"></uni-icons>
					<text>参与人数: {{ voteInfo.participantCount }}人</text>
				</view>
				<view class="meta-item">
					<uni-icons type="time" size="16" color="#666"></uni-icons>
					<text>{{ formatTimeRange(voteInfo.startTime, voteInfo.endTime) }}</text>
				</view>
			</view>
		</view>

		<!-- 投票结果提示 -->
		<view class="vote-success-tip">
			<uni-icons type="success" size="20" color="#4cd964"></uni-icons>
			<text>您已成功投票！</text>
		</view>

		<!-- 结果可视化区域 -->
		<view class="result-chart">
			<view class="chart-title">当前投票结果</view>
			<!-- 图表容器 - 使用ec-canvas适配Uniapp -->
			<!-- <ec-canvas type="pie" canvas-id="voteResultChart" :ec="chartOption" class="chart-content"></ec-canvas> -->
			<view style="width:750rpx; height:750rpx">
				<l-echart ref="chartRef"></l-echart>
			</view>
		</view>
		<!-- 用户选择标记 -->
		<view class="result-chart" v-if="voteInfo.optionContent" style="color:#1890ff">
			<uni-icons type="checkmark" size="16" color="#fff"></uni-icons>
			<text>您的选择是：{{voteInfo.optionContent}}</text>
		</view>
		<!-- 详细结果列表 -->
		<view class="options-list">
			<view class="list-title">选项详情</view>

			<view class="option-item" v-for="(option, index) in voteInfo.voteOptions" :key="index"
				:class="{ 'user-selected': option.isUserSelected }">
				<!-- 选项信息 -->
				<view class="option-info">
					<!-- <view class="option-icon" :style="{ backgroundColor: option.color }">
						{{ String.fromCharCode(65 + index) }}
					</view> -->
					<view class="option-text">
						<view class="option-name">{{ option.optionContent }}</view>
						<!-- <view class="option-desc">{{ option.desc }}</view> -->
					</view>
				</view>

				<!-- 投票数据 -->
				<view class="option-stats">
					<view class="votes-count">{{ option.voteCount }}票</view>
					<view class="progress-bar">
						<view class="progress"
							:style="{ width: option.percentage + '%', backgroundColor:voteLightColors[index] }">
						</view>
					</view>
					<view class="percentage">{{ option.percentage }}%</view>
				</view>


			</view>
		</view>

		<!-- 操作按钮区 -->
		<view class="action-buttons">
			<button class="primary-btn" @click="goTovoteInfoList">
				查看更多活动
			</button>
			<button class="secondary-btn" @click="refreshResult" v-if="voteInfo.status == '1'">
				<uni-icons type="refresh" size="16" color="#333"></uni-icons>
				刷新结果
			</button>
		</view>
	</view>
</template>

<script setup>
	import CustomNavbar from '@/components/CustomNavbar.vue';
	import {
		ref,
		onMounted,
		computed,
		watch
	} from 'vue';
	import {
		useRoute,
		useRouter
	} from 'vue-router';
	import * as echarts from 'echarts';
	import {
		getVoteResult
	} from '@/api/vote';
	import {
		onLoad,
		onShow
	} from "@dcloudio/uni-app";
	// 路由和导航
	const route = useRoute();
	const router = useRouter();
	const totalVotes = ref(0);
	const chartRef = ref(null);

	// 活动数据
	const voteInfo = ref({
		voteId: '',
		voteTitle: '',
		voteDesc: '',
		status: '1', // 1-进行中 2-已结束
		startTime: '',
		endTime: '',
		participantCount: 0,
		voteOptions: []
	});
	const dataObj = ref({})
	const voteLightColors = [
		'#1890ff', // 蓝色（主色调）
		'#52c41a', // 绿色
		'#faad14', // 橙色
		'#f5222d', // 红色
		'#722ed1', // 紫色
		'#13c2c2', // 青色
		'#fa8c16', // 橙红色
		'#7cb305', // 浅绿色
		'#eb2f96', // 粉红色
		'#8c8c8c', // 灰色
		'#096dd9', // 深蓝色
		'#d48806' // 深黄色
	];
	// 图表数据
	const chartData = ref([]);

	// 获取投票结果数据
	const fetchVoteResult = async () => {
		try {
			const voteInfoId = dataObj.value.voteId;
			const res = await getVoteResult(voteInfoId);
			totalVotes.value = res.data.voteOptions.reduce((sum, option) => sum + option.voteCount, 0);
			const t = res.data.voteOptions.map((option, index) => {
				const percentage = totalVotes.value > 0 ? (option.voteCount / totalVotes.value) * 100 : 0;
				return {
					...option,
					percentage: percentage.toFixed(2),
					color: voteLightColors[index],
					name: option.optionContent,
					value: option.voteCount
				};
			})
			res.data.voteOptions = t
			voteInfo.value = res.data;
			//返回图表数据
			chartData.value = res.data.voteOptions;
			// 更新图表数据
			// updateChartData(res.data.voteOptions);
		} catch (error) {
			console.error('获取投票结果失败:', error);
			uni.showToast({
				title: '获取结果失败',
				icon: 'none',
				duration: 2000
			});
		}
	};

	// 更新图表数据
	const updateChartData = () => {
		chartOption.value.series[0].data = voteInfo.value.voteOptions.map(option => ({
			value: option.voteCount,
			name: option.optionContent,
			itemStyle: {
				color: option.color
			}
		}));
	};

	// 格式化时间范围
	const formatTimeRange = (start, end) => {
		const startDate = new Date(start);
		const endDate = new Date(end);
		return `${startDate.toLocaleDateString()} - ${endDate.toLocaleDateString()}`;
	};

	// 刷新结果
	const refreshResult = () => {
		uni.showLoading({
			title: '刷新中...'
		});
		fetchVoteResult().then(() => {
			uni.hideLoading();
			uni.showToast({
				title: '已更新最新结果',
				icon: 'none',
				duration: 1500
			});
		});
	};

	// 导航返回
	const navigateBack = () => {
		router.back();
	};

	// 前往活动列表
	const goTovoteInfoList = () => {
		router.push('/pages/voteAllList/voteAllList');
	};

	// 分享结果
	const shareResult = () => {
		// 调用Uniapp分享API
		uni.share({
			provider: 'weixin',
			scene: 'WXSceneSession',
			type: 0,
			title: `我参与了"${voteInfo.value.title}"的投票`,
			summary: `快来看看"${voteInfo.value.title}"的投票结果吧！`,
			success: () => {
				uni.showToast({
					title: '分享成功',
					icon: 'none'
				});
			},
			fail: (err) => {
				console.error('分享失败:', err);
			}
		});
	};
	
	
	// 页面加载时获取数据
	onMounted(() => {
		chartRef.value.init(echarts, chart => {
			let option = {
				title: {
					text:voteInfo.value.voteTitle,
					// subtext: '纯属虚构',
					left: 'center'
				},
				tooltip: {
					trigger: 'item'
				},
				legend: {
					orient: 'vertical',
					left: 'left',
					show:false
				},
				series: [{
					name: '访问来源',
					type: 'pie',
					radius: '50%',
					data:chartData.value,
					emphasis: {
						itemStyle: {
							shadowBlur: 10,
							shadowOffsetX: 0,
							shadowColor: 'rgba(0, 0, 0, 0.5)'
						}
					}
				}]
			}
			chart.setOption(option);
		});
	});
	onLoad(params => {
		dataObj.value = JSON.parse(decodeURIComponent(params.data))
		fetchVoteResult();
	})
</script>

<style scoped>
	.vote-result-page {
		min-height: 100vh;
		background-color: #f5f5f7;
		padding-bottom: 80rpx;
	}

	/* 导航栏样式 */
	.navbar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 100rpx;
		padding: 0 30rpx;
		background-color: #fff;
		border-bottom: 1px solid #eee;
	}

	.title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}

	/* 活动卡片样式 */
	.voteInfo-card {
		background-color: #fff;
		border-radius: 20rpx;
		padding: 30rpx;
		margin: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.voteInfo-status {
		display: inline-block;
		padding: 8rpx 20rpx;
		border-radius: 20rpx;
		font-size: 24rpx;
		margin-bottom: 20rpx;
	}

	.voteInfo-status.active {
		background-color: #e6f7ee;
		color: #00b42a;
	}

	.voteInfo-status.ended {
		background-color: #fef2f2;
		color: #f53f3f;
	}

	.voteInfo-title {
		font-size: 34rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
		line-height: 1.4;
	}

	.voteInfo-meta {
		display: flex;
		justify-content: space-between;
		color: #666;
		font-size: 26rpx;
	}

	.meta-item {
		display: flex;
		align-items: center;
		gap: 8rpx;
	}

	/* 投票成功提示 */
	.vote-success-tip {
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 10rpx;
		background-color: #f0f7ff;
		color: #1890ff;
		font-size: 28rpx;
		padding: 20rpx;
		margin: 0 20rpx 20rpx;
		border-radius: 10rpx;
	}

	/* 图表区域样式 */
	.result-chart {
		background-color: #fff;
		border-radius: 20rpx;
		padding: 30rpx;
		margin: 0 20rpx 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.chart-title {
		font-size: 30rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
		text-align: center;
	}

	.chart-content {
		width: 100%;
		height: 400rpx;
	}

	/* 选项列表样式 */
	.options-list {
		background-color: #fff;
		border-radius: 20rpx;
		padding: 30rpx;
		margin: 0 20rpx 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.list-title {
		font-size: 30rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
		padding-bottom: 15rpx;
		border-bottom: 1px solid #eee;
	}

	.option-item {
		display: flex;
		flex-direction: column;
		padding: 20rpx 0;
		border-bottom: 1px solid #f5f5f5;
		position: relative;
	}

	.option-item:last-child {
		border-bottom: none;
	}

	.option-item.user-selected {
		background-color: rgba(24, 144, 255, 0.05);
		border-radius: 10rpx;
		padding: 20rpx;
		margin: 5rpx 0;
	}

	.option-info {
		display: flex;
		align-items: center;
		margin-bottom: 15rpx;
	}

	.option-icon {
		width: 50rpx;
		height: 50rpx;
		border-radius: 50%;
		color: #fff;
		font-size: 28rpx;
		font-weight: bold;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 20rpx;
	}

	.option-text {
		flex: 1;
	}

	.option-name {
		font-size: 30rpx;
		color: #333;
		margin-bottom: 5rpx;
	}

	.option-desc {
		font-size: 24rpx;
		color: #666;
		line-height: 1.4;
	}

	.option-stats {
		width: 100%;
	}

	.votes-count {
		font-size: 26rpx;
		color: #666;
		margin-bottom: 10rpx;
	}

	.progress-bar {
		width: 100%;
		height: 20rpx;
		background-color: #f5f5f5;
		border-radius: 10rpx;
		overflow: hidden;
		margin-bottom: 10rpx;
	}

	.progress {
		height: 100%;
		border-radius: 10rpx;
		transition: width 0.5s ease;
	}

	.percentage {
		font-size: 26rpx;
		font-weight: bold;
		color: #333;
		text-align: right;
	}

	.selected-tag {
		position: absolute;
		top: 20rpx;
		right: 0;
		display: flex;
		align-items: center;
		gap: 5rpx;
		background-color: #1890ff;
		color: #fff;
		font-size: 24rpx;
		padding: 5rpx 15rpx;
		border-radius: 20rpx;
	}

	/* 操作按钮样式 */
	.action-buttons {
		display: flex;
		gap: 20rpx;
		padding: 0 20rpx;
		position: fixed;
		bottom: 20rpx;
		left: 0;
		right: 0;
	}

	.primary-btn {
		flex: 1;
		height: 90rpx;
		line-height: 90rpx;
		background-color: #1890ff;
		color: #fff;
		border-radius: 45rpx;
		font-size: 30rpx;
		border: none;
	}

	.secondary-btn {
		flex: 1;
		height: 90rpx;
		line-height: 90rpx;
		background-color: #fff;
		color: #333;
		border-radius: 45rpx;
		font-size: 30rpx;
		border: 1px solid #eee;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 10rpx;
	}
</style>